package org.apache.cordova;

import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.rococoa.cocoa.foundation.NSString;

import addressbook.model.ABPerson;
import addressbook.test.MacOsAddressBook;

/**
 * MacOs {@link ContactAccessor} implementation.
 * TODO CJO - not finished at all. Implement save, getById ...
 * @author Cyril Joui
 */
public class MacOsContactAccessor extends ContactAccessor {

	/**
	 * {@inheritDoc}
	 * @see org.apache.cordova.ContactAccessor#save(org.json.JSONObject)
	 */
	@Override
	public String save(JSONObject contact) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * {@inheritDoc}
	 * @see org.apache.cordova.ContactAccessor#search(org.json.JSONArray, org.json.JSONObject)
	 */
	@Override
	public JSONArray search(JSONArray filter, JSONObject options) {
		System.out.println("search mac ..");
		MacOsAddressBook addressBook = new MacOsAddressBook();
		List<ABPerson> people = addressBook.findAllPeople();
		//System.out.println("All people: " + people);

		int currentIndex = 0;
		JSONArray result = new JSONArray();
		for (Iterator iterator = people.iterator(); iterator.hasNext();) {
			ABPerson person = (ABPerson) iterator.next();
			// Get properties from Macos
			String firstName = MacOsAddressBook.getNamePartValueForPropert(person, 
					"" + NSString.getGlobalString(MacOsAddressBook.abFrameworkName, "kABFirstNameProperty"));
			String lastName = MacOsAddressBook.getNamePartValueForPropert(person, 
					"" + NSString.getGlobalString(MacOsAddressBook.abFrameworkName, "kABLastNameProperty"));
			String displayName = firstName + " " + lastName;


			try {
				// Contact obj
				JSONObject contact = new JSONObject();

				// Name
				JSONObject nameObject = new JSONObject();
				nameObject.put("familyName", lastName);
				nameObject.put("givenName", firstName);
				nameObject.put("middleName", "");
				nameObject.put("honorificPrefix", "");
				nameObject.put("honorificSuffix", "");
				nameObject.put("formatted", displayName);

				contact.put("id", "" + currentIndex);
				contact.put("rawId", "" + currentIndex);
				contact.put("displayName", displayName);
				contact.put("name", nameObject);

				// Add to result
				result.put(contact);
				// TODO more ...
				currentIndex++;
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		addressBook.releaseAll();
		// TODO Auto-generated method stub
		return result;
	}

	/**
	 * {@inheritDoc}
	 * @see org.apache.cordova.ContactAccessor#getContactById(java.lang.String)
	 */
	@Override
	public JSONObject getContactById(String id) throws JSONException {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * {@inheritDoc}
	 * @see org.apache.cordova.ContactAccessor#remove(java.lang.String)
	 */
	@Override
	public boolean remove(String id) {
		// TODO Auto-generated method stub
		return false;
	}

}
